package basic.courseLearn14.bitOperation;

import org.junit.Test;

//判断一个数是否是2/4 的整数幂
public class CheckPowerCase {

    @Test
    public void testIsPowerOfTwo(){
        System.out.println(2+" is power of 2: "+isPowerOfTwo(2));
        System.out.println(4+" is power of 2: "+isPowerOfTwo(4));
        System.out.println(8+" is power of 2: "+isPowerOfTwo(8));
        System.out.println(16+" is power of 2: "+isPowerOfTwo(16));
        System.out.println(15+" is power of 2: "+isPowerOfTwo(15));
        System.out.println(-15+" is power of 2: "+isPowerOfTwo(-15));
    }

    @Test
    public void testIsPowerOfFour(){
        System.out.println(1+" is power of 4: "+isPowerOfFour(1));
        System.out.println(2+" is power of 4: "+isPowerOfFour(2));
        System.out.println(4+" is power of 4: "+isPowerOfFour(4));
        System.out.println(8+" is power of 4: "+isPowerOfFour(8));
        System.out.println(16+" is power of 4: "+isPowerOfFour(16));
        System.out.println(15+" is power of 4: "+isPowerOfFour(15));
        System.out.println(-15+" is power of 4: "+isPowerOfFour(-15));
    }

    //返回符号位
    public int getSign(int n){
        return (n >> 31);
    }


    //判断一个数是否是2的整数幂
    public boolean isPowerOfTwo(int n) {
        //负数直接返回false
        if (getSign(n)!= 0){
            return false;
        }
        //正数情况，判断是否只包含一个1，及取最右侧的1，判断和自身是否相等
        int rightOne = n & (~n + 1);
        return rightOne == n;
    }

    //判断一个数是否是4的整数幂
    public boolean isPowerOfFour(int n) {
        // 1. 是否为2的整数幂，确保只有1个1
        if (!isPowerOfTwo(n)) {
            return false;
        }
        // 2. 和010101进行与操作，判断1的位置
        if ((n & 0x55555555) == 0){
            return false;
        }
        return true;
    }
}
